<?php

namespace Jinxing\Admin\Repositories;

use Illuminate\Support\Arr;
use Jinxing\Admin\Models\Role;
use Littlebug\Repository\Repository;
use Illuminate\Support\Facades\DB;

class RoleRepository extends Repository
{
    public function __construct(Role $model)
    {
        parent::__construct($model);
    }

    /**
     * 添加角色
     *
     * @param $condition
     *
     * @return int
     * @throws \Throwable
     */
    public function deleteRole($condition)
    {
        return DB::transaction(function () use ($condition) {
            $this->delete($condition);

            return PermissionRepository::instance()->delete(['role_id' => Arr::get($condition, 'id')]);
        });
    }

    /**
     * 修改权限
     *
     * @param integer $role_id     角色ID
     * @param array   $data        修改数据
     * @param array   $permissions 权限信息
     *
     * @return array
     * @throws \Throwable
     */
    public function updatePermissions($role_id, $data, $permissions)
    {
        return DB::transaction(function () use ($role_id, $data, $permissions) {
            $this->update($role_id, $data);

            return $this->first(['id' => $role_id])->perms()->sync($permissions);
        });
    }
}
